//
//  GSGooglePlus.m
//  AgileNYC
//
//  Created by German on 27.06.14.
//  Copyright (c) 2014 Softlegion. All rights reserved.
//


#import "GSGooglePlus.h"
#import "GTLPlusPerson.h"
#import "SGSUtils.h"
#import "SGSServerManagerConsts.h"
#import "GTLPlusConstants.h"


static NSString * const kClientID = @"1053622429674-eedv3i021doop6nedo07ssfrbfge9kqj.apps.googleusercontent.com";
//static NSString * const kClientID = @"1053622429674-m0qqv3p5btcp6gerns4100f8p7a4kl5n.apps.googleusercontent.com";

@interface GSGooglePlus() <GPPSignInDelegate>

@property (copy, nonatomic) GSSuccessfullBlock loginSuccessfulBlock;
@property (copy, nonatomic) GSFailureBlock loginFailureBlock;
@property (copy, nonatomic) GSImageReceivedBlock imageReceivedBlock;

@end

@implementation GSGooglePlus

- (instancetype)init
{
    self = [super init];
    if (self) {
        GPPSignIn *signIn = [GPPSignIn sharedInstance];

        //signIn.clientID = googlePlusAppId;
        signIn.clientID = kClientID;
        signIn.shouldFetchGooglePlusUser = YES;
        signIn.shouldFetchGoogleUserEmail = YES;
        
        signIn.delegate = self;
        
        //signIn.
        
        /*signIn.scopes = [NSArray arrayWithObjects:kGTLAuthScopePlusLogin,
                                                    kGTLAuthScopePlusMe,
                                                    kGTLAuthScopePlusUserinfoEmail,
                                                    kGTLAuthScopePlusUserinfoProfile, nil];*/
        
        signIn.scopes = [NSArray arrayWithObjects:
                                                     kGTLAuthScopePlusMe,
                                                     kGTLAuthScopePlusUserinfoEmail,
                                                     kGTLAuthScopePlusUserinfoProfile, nil];

        //[signIn signOut];

        //[[GPPSignIn sharedInstance] trySilentAuthentication];
        //[GPPDeepLink setDelegate:self];
        //[GPPDeepLink readDeepLinkAfterInstall];
    }
    return self;
}

-(void) loginToGooglePlus:(int) reserved
                onSuccess:(void(^)(void)) success
                onFailure:(void(^)(NSError * error)) failure {

    GPPSignIn *signIn = [GPPSignIn sharedInstance];

    self.loginSuccessfulBlock = success;
    self.loginFailureBlock = failure;
    //self.imageReceivedBlock = imageReceived;

    if (![signIn authentication]) {
      //  if (![signIn trySilentAuthentication]) {
        [signIn authenticate];
      /*  } else {
            if (success) {
                success([self populateUserData]);
            }
        }*/
        
    }
    
    
}

- (void)finishedWithAuth:(GTMOAuth2Authentication *)auth
                   error:(NSError *)error {
    if (error) {
        
        if (self.loginFailureBlock) {
            self.loginFailureBlock(error);
        }
    } else {
        
        if (self.loginSuccessfulBlock) {
            self.loginSuccessfulBlock();
        }
    }
}

- (void)requestUserInfoWithImageHeight:(NSInteger) height
                                 Width:(NSInteger) width
                             onSuccess:(void(^)(NSDictionary * userInfo)) success
                       onImageReceived:(void(^)(NSData* userImage)) imageReceived
                             onFailure:(void(^)(NSError * error)) failure {
    [self requestUserInfo:0
        onSuccess:^(NSDictionary *userInfo) {
            if (success) {
                success(userInfo);
            }
            
            [self requestUserImage:0
                 onSuccess:^(NSData *userImage) {
                     if (imageReceived) {
                         imageReceived(userImage);
                     }
                 } onFailure:^(NSError *error) {
                     if (failure) {
                         failure(error);
                     }
                 }];
            
        } onFailure:^(NSError *error) {
            if (failure) {
                failure(error);
            }
        }];
    
}

- (void)requestUserInfo:(int) reserved
              onSuccess:(void(^)(NSDictionary * userInfo)) success
              onFailure:(void(^)(NSError * error)) failure {
    
    GPPSignIn *signIn = [GPPSignIn sharedInstance];
    NSMutableDictionary * dict = [NSMutableDictionary dictionary];
    
    if (signIn.userEmail) {
        [dict setObject:[GPPSignIn sharedInstance].userEmail forKey:userEmailKey];
    }
    
    GTLPlusPerson *person = [GPPSignIn sharedInstance].googlePlusUser;
    if (person == nil) {
        if (failure) {
            NSError * error = [[NSError alloc] initWithDomain:@"Unable to populate data" code:0 userInfo:nil];
            failure(error);
        }
    }
    
    if (person.tagline) [dict setObject:person.tagline forKey:userMemoKey];
    if (person.name.givenName) [dict setObject:person.name.givenName forKey:userFirstNameKey];
    if (person.name.familyName) [dict setObject:person.name.familyName forKey:userLastNameKey];
    if (person.currentLocation) [dict setObject:person.currentLocation forKey:userStateKey];
    if (person.identifier) [dict setObject:person.identifier forKey:userSocialIdKey];
    
    for (GTLPlusPersonOrganizationsItem * item in person.organizations) {
        if ([item.primary boolValue]) {
            if (item.name) [dict setObject:item.name forKey:userCompanyNameKey];
            if (item.title) [dict setObject:item.title forKey:userTitleKey];
            break;
        }
    }
    
    for (GTLPlusPersonPlacesLivedItem * item in person.placesLived) {
        if ([item.primary boolValue]) {
            if (item.value) [dict setObject:item.value forKey:userStateKey];
            break;
        }
    }
    
    if (success) {
        success(dict);
    }
    
}

- (void)requestUserImage:(int) reserved
              onSuccess:(void(^)(NSData* userImage)) success
              onFailure:(void(^)(NSError * error)) failure {
    GTLPlusPerson *person = [GPPSignIn sharedInstance].googlePlusUser;
    if (person == nil) {
        if (failure) {
            NSError * error = [[NSError alloc] initWithDomain:@"Unable to get user image from Google+" code:0 userInfo:nil];
            failure(error);
        }
    }
    
    // Load avatar image asynchronously, in background
    dispatch_queue_t backgroundQueue =
    dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    
    dispatch_async(backgroundQueue, ^{
        NSData *avatarData = nil;
        NSString *imageURLString = person.image.url;
        if (imageURLString) {
            NSURL *imageURL = [NSURL URLWithString:imageURLString];
            avatarData = [NSData dataWithContentsOfURL:imageURL];
        }
        
        if (avatarData) {
            // Update UI from the main thread when available
            dispatch_async(dispatch_get_main_queue(), ^{
                //self.userAvatar.image = [UIImage imageWithData:avatarData];
                if (success) {
                    success(avatarData);
                }
            });
        } else {
            if (success) {
                success(nil);
            }
        }
    });
    

}


-(NSDictionary*) populateUserData {
    GPPSignIn *signIn = [GPPSignIn sharedInstance];
    NSMutableDictionary * dict = [NSMutableDictionary dictionary];
    
    if (signIn.userEmail) {
        [dict setObject:[GPPSignIn sharedInstance].userEmail forKey:userEmailKey];
    }
    
    GTLPlusPerson *person = [GPPSignIn sharedInstance].googlePlusUser;
    if (person == nil) {
        return dict;
    }
    
    if (person.tagline) [dict setObject:person.tagline forKey:userMemoKey];
    if (person.name.givenName) [dict setObject:person.name.givenName forKey:userFirstNameKey];
    if (person.name.familyName) [dict setObject:person.name.familyName forKey:userLastNameKey];
    if (person.currentLocation) [dict setObject:person.currentLocation forKey:userStateKey];
    if (person.identifier) [dict setObject:person.identifier forKey:userSocialIdKey];
    
    for (GTLPlusPersonOrganizationsItem * item in person.organizations) {
        if ([item.primary boolValue]) {
            if (item.name) [dict setObject:item.name forKey:userCompanyNameKey];
            if (item.title) [dict setObject:item.title forKey:userTitleKey];
            break;
        }
    }
    
    for (GTLPlusPersonPlacesLivedItem * item in person.placesLived) {
        if ([item.primary boolValue]) {
            if (item.value) [dict setObject:item.value forKey:userStateKey];
            break;
        }
    }
    
    
    // Load avatar image asynchronously, in background
    dispatch_queue_t backgroundQueue =
    dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    
    dispatch_async(backgroundQueue, ^{
        NSData *avatarData = nil;
        NSString *imageURLString = person.image.url;
        if (imageURLString) {
            NSURL *imageURL = [NSURL URLWithString:imageURLString];
            avatarData = [NSData dataWithContentsOfURL:imageURL];
        }
        
        if (avatarData) {
            // Update UI from the main thread when available
            dispatch_async(dispatch_get_main_queue(), ^{
                //self.userAvatar.image = [UIImage imageWithData:avatarData];
                if (self.imageReceivedBlock) {
                    self.imageReceivedBlock(avatarData);
                }
            });
        } else {
            if (self.imageReceivedBlock) {
                self.imageReceivedBlock(nil);
            }
        }
        
    });
                   
    return dict;
}

#pragma mark - Connect To Google Plus Without SDK

/*
-(void) loginWithGooglePlus:(GSUser*) currentUser
                 onComplete: (GSCompletionBlock) completionBlock {
    
    self.currentUser = currentUser;
    //self.loginCompletionBlock = completionBlock;
    
    NSString * urlString = [NSString stringWithFormat:
                            @"https://accounts.google.com/o/oauth2/auth?"
                            "scope=%@"
                            "&redirect_uri=%@"
                            "&response_type=%@"
                            "&client_id=%@"
                            "&state=%@"
                            ,@"email profile"
                            ,googlePlusRedirectURL
                            ,@"code"
                            ,googlePlusAppId
                            ,googlePlusStateString
                            ];
    
    self.currentAuthHost = [[NSURL URLWithString:googlePlusRedirectURL] host];
    //self.currentToken = currentUser.googlePlusToken;
    self.currentTokenKey = googlePlusTokenKey;
    self.currentExpiredKey = googlePlusExpiredKey;
    self.currentUserIDKey = googlePlusUserIdKey;
    self.currentErrorKey = googlePlusErrorKey;
    
    NSString* webUrlString = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
    [self showExternalLoginDialogWithURL:webUrlString caption:@"Login to Google+"];
}

-(void) getUserFromGooglePlus:(GSUser*) currentUser
                   onComplete: (GSCompletionBlock) completionBlock {
    
    self.currentUser = currentUser;
    
    //[self initRequestManagerWithURL:[NSString stringWithFormat:@"%@%@%@", googlePlusURL, @"people/me/", currentUser.googlePlusToken.userID]];
    [self initRequestManagerWithURL:[NSString stringWithFormat:@"%@%@", googlePlusURL, @"people/me"]];
    
    NSDictionary * params = [NSDictionary dictionaryWithObjectsAndKeys:
                             currentUser.tokenGooglePlus,@"access_token",
                             nil];
    
    //[self startSpinnerOnView:nil];
    
    [self.requestOperationManager GET:@"me"
                           parameters:params
                              success:^(AFHTTPRequestOperation *operation, NSDictionary * responseObject) {
                                  //NSLog(@"JSON: %@", responseObject);
                                  
                                  for (NSString * key in [responseObject allKeys]) {
                                      
                                      if ([key isEqualToString:@"displayName"]) {
                                          NSString * displayName = [responseObject objectForKey:key];
                                          NSArray * sepName = [displayName componentsSeparatedByString:@" "];
                                          if ([sepName count]>=2) {
                                              currentUser.lastName = [sepName objectAtIndex:1];
                                          }
                                          if ([sepName count] >=1) {
                                              currentUser.firstName = [sepName objectAtIndex:0];
                                          }
                                      } else if ([key isEqualToString:@"last_name"]) {
                                          currentUser.lastName = [responseObject objectForKey:key];
                                      } else if ([key isEqualToString:@"id"]) {
                                          //currentUser.facebookToken.userID = [responseObject objectForKey:key];
                                      } else if ([key isEqualToString:@"email"]) {
                                          currentUser.eMail = [responseObject objectForKey:key];
                                      } else if ([key isEqualToString:@"website"]) {
                                          currentUser.webSite = [responseObject objectForKey:key];
                                      } else if ([key isEqualToString:@"image"]) {
                                          //NSDictionary * imageDic = [responseObject objectForKey:key];
                                          //currentUser.city = [locDic objectForKey:@"url"];
                                      }
                                      
                                  }
                                  
                                  if (completionBlock) {
                                      completionBlock(YES,nil, operation.response.statusCode);
                                  }
                                  
                                  //[self stopSpinner];
                              }
                              failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                                  if (completionBlock) {
                                      completionBlock(NO,error,operation.response.statusCode);
                                  }
                                  
                                  //[self stopSpinner];
                              }];
    
}
*/

                   
@end
